package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @description
 * @author: xu1
 **/
@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired//autowired默认是按照 类型注入的，类型找不着，找名字注入
    //如果想直接 按照 名称注入 再加 一个 @Qualifier
    //@Resource 后边 括号 参数 name 写死 就不会按照 类型找了
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(method= RequestMethod.GET)
    public Result findAll(){
        return new Result(true, StatusCode.OK,"查询成功",spitService.findAll());
    }

    //value = "/{spitId} 注意斜杠不要写错value = "{/spitId}
    @RequestMapping(value = "/{spitId}",method= RequestMethod.GET)
    public Result findById(@PathVariable String spitId){
        return new Result(true, StatusCode.OK,"查询成功",spitService.findById(spitId));
    }

    @RequestMapping(method= RequestMethod.POST)
    public Result sava(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.OK,"保存成功");
    }

    @RequestMapping(value = "/{spitId}",method= RequestMethod.PUT)
    public Result update(@PathVariable String spitId,@RequestBody Spit spit){
        spit.set_id(spitId);
        spitService.update(spit);
        return new Result(true, StatusCode.OK,"修改成功");
    }

    @RequestMapping(value = "/{spitId}",method= RequestMethod.DELETE)
    public Result delete(@PathVariable String spitId){
        spitService.deleteById(spitId);
        return new Result(true, StatusCode.OK,"删除成功");
    }

    //
    @RequestMapping(value = "/comment/{parentid}/{page}/{size}",method= RequestMethod.GET)
    public Result findByParentid(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        Page<Spit> pageData = spitService.findByParentid(parentid, page, size);
        return new Result(true,StatusCode.OK,"查询成功",
         new PageResult<Spit>(pageData.getTotalElements(),pageData.getContent()));
    }

    //
    @RequestMapping(value = "/thumbup/{spitId}",method= RequestMethod.PUT)
    public Result thumbup(@PathVariable String spitId){
        //判断 当前 用户 是否已经点赞
        //没有认证， 暂时userid 写死
        String userid = "111";
        if(redisTemplate.opsForValue().get("thumbup_"+userid)!=null){
            return new Result(false, StatusCode.REPERROR,"不能重复点赞");
        }

        //Object o = redisTemplate.opsForValue().get("thumbup_" + userid);
        //可用来判断有无。

        spitService.thumbup(spitId);
        redisTemplate.opsForValue().set("thumbup_"+userid, 1);//1是随便存的 当标记用。
        return new Result(true, StatusCode.OK,"点赞成功");
    }

















}
